package com.etc.web;

import com.etc.po.UserInfoPo;
import com.etc.services.UserServiceInf;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * restcontroller 返回结果不走视图解析去
 * java对象的json格式转换
 */
@RestController
public class AjaxController {

    @RequestMapping(value="api/getall.action", produces="application/json;charset=UTF-8")
    public String getUserInfo(HttpServletResponse respo) {
//        respo.setCharacterEncoding("UTF-8");

        CodeMessage cm = new CodeMessage();
        cm.setCode("200");
        cm.setMessage("ajax调用成功");

        List<UserInfoVo> list = new ArrayList<UserInfoVo>();


        list.add(new UserInfoVo("tom1", "123456", new Date(40, 1, 1), 10));
        list.add(new UserInfoVo("tom2", "123456", new Date(40, 1, 1), 10));
        list.add(new UserInfoVo("tom3", "123456", new Date(40, 1, 1), 10));
        list.add(new UserInfoVo("tom4", "123456", new Date(40, 1, 1), 10));

        cm.setData(list);

        // java对象直接转换　文字
        ObjectMapper om = new ObjectMapper();

        String result = null;
        try {
            result = om.writeValueAsString(cm);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return result;


    }

//    注入 service
    @Autowired
    UserServiceInf serviceInf;

    @RequestMapping(value="api/getall1.action", produces="application/json;charset=UTF-8")
    public String getUserInfo1(){

        CodeMessage cm = new CodeMessage();
        cm.setCode("200");
        cm.setMessage("ajax调用成功");


        // 连接数据库？？？？
        List<UserInfoPo> polist = serviceInf.getAll();

        cm.setData(polist);

        // java对象直接转换　文字
        ObjectMapper om = new ObjectMapper();

        String result = null;
        try {
            result = om.writeValueAsString(cm);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return result;
    }
}
